package com.example.project.projectspringcloud.controller.front.user;

import com.example.project.projectspringcloud.common.Constants;
import com.example.project.projectspringcloud.common.OperationException;
import com.example.project.projectspringcloud.controller.BaseController;
import com.example.project.projectspringcloud.entity.Page;
import com.example.project.projectspringcloud.entity.RespBody;
import com.example.project.projectspringcloud.entity.sys.Dictionary;
import com.example.project.projectspringcloud.entity.user.Collect;
import com.example.project.projectspringcloud.entity.user.User;
import com.example.project.projectspringcloud.entity.video.Video;
import com.example.project.projectspringcloud.service.sys.SysDictionaryService;
import com.example.project.projectspringcloud.service.user.UserCollectService;
import com.example.project.projectspringcloud.service.user.UserService;
import com.example.project.projectspringcloud.service.video.VideoService;
import com.example.project.projectspringcloud.utils.ObjectUtil;
import com.example.project.projectspringcloud.utils.WebUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Api(value = "用户端收藏Controller")
@RequestMapping(value = "/personal/collect/{type}/{operation}")
@Controller
public class CollectController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(CollectController.class);

    @Autowired
    private UserCollectService userCollectService;

    @Autowired
    private VideoService videoService;

    @Autowired
    private UserService userService;

    @Autowired
    private SysDictionaryService sysDictionaryService;

    @ApiOperation(value = "用户收藏列表", notes = "返回用户收藏列表")
    @GetMapping(value = {"", "/list"})
    public String list(@ApiParam(value = "type: 1. 用户, 2. 视频") @PathVariable("type") Integer type,
                       @ApiParam(value = "operation: 1. 喜欢, 2. 收藏") @PathVariable("operation") Integer operation,
                       @ApiParam(value = "content-type: 内容分类: 如果 type = 1, content-type: 4: 摄影师, 5: 编剧. 如果 type = 2, content=type: 1: 工作, 2: 婚恋, 3: 网红 ...")
                       @RequestParam(value = "contentType", required = false) Integer contentType,
                       Page page, Model model) {
        Collect collect = new Collect();
        collect.setType(type);
        collect.setOperation(operation);
        collect.setUserId(getCurrentUser().getId());

        List<Collect> collects = userCollectService.list(page, collect);
        Set<Integer> dataIds = collects.stream().map(Collect::getDataId).collect(Collectors.toSet());

        model.addAttribute("page", new Page<Collect>(collects));
        model.addAttribute("collect", collect);
        model.addAttribute("type", type);
        model.addAttribute("contentType", contentType);

        if (!dataIds.isEmpty()) {
            // 请求类型为获取收藏用户
            if (Constants.ContentType.TYPE_USER == type) {
                List<User> users = userService.list(dataIds, contentType);
                model.addAttribute("users", users);
                List<Dictionary> dictionaries = sysDictionaryService.list(new Dictionary("user-type"), null);
                model.addAttribute("dictionaries", dictionaries);
            }
            // 请求类型为获取收藏视频
            else if (Constants.ContentType.TYPE_VIDEO == type) {
                List<Video> videos = videoService.list(dataIds, contentType);
                model.addAttribute("videos", videos);
                List<Dictionary> dictionaries = sysDictionaryService.list(new Dictionary("production-type"), null);
                model.addAttribute("dictionaries", dictionaries);
            }
        }

        // 请求类型为获取收藏用户
        if (Constants.ContentType.TYPE_USER == type) {
            return isMobile() ? "m/content/collect/collect-list" : "content/collect/collect-user";
        }
        // 请求类型为获取收藏视频
        else if (Constants.ContentType.TYPE_VIDEO == type) {
            return isMobile() ? "m/content/collect/collect-list" : "content/collect/collect-production";
        } else {
            return null;
        }
    }

    @ApiOperation(value = "API用户收藏列表", notes = "返回用户收藏列表")
    @GetMapping(value = "/api/list")
    @ResponseBody
    public RespBody list(@ApiParam(value = "type: 1. 用户, 2. 视频") @PathVariable("type") Integer type,
                       @ApiParam(value = "operation: 1. 喜欢, 2. 收藏") @PathVariable("operation") Integer operation,
                       @ApiParam(value = "content-type: 内容分类: 如果 type = 1, content-type: 4: 摄影师, 5: 编剧. 如果 type = 2, content=type: 1: 工作, 2: 婚恋, 3: 网红 ...")
                       @RequestParam(value = "contentType", required = false) Integer contentType, Page page) {
        Collect collect = new Collect();
        collect.setType(type);
        collect.setOperation(operation);
        collect.setUserId(getCurrentUser().getId());

        List<Collect> collects = userCollectService.list(page, collect);
        Set<Integer> dataIds = collects.stream().map(Collect::getDataId).collect(Collectors.toSet());

        Map result = new HashMap();
        result.put("page", new Page<Collect>(collects));
        result.put("collect", collect);
        result.put("type", type);
        result.put("contentType", contentType);

        if (!dataIds.isEmpty()) {
            // 请求类型为获取收藏用户
            if (Constants.ContentType.TYPE_USER == type) {
                List<User> users = userService.list(dataIds, contentType);
                result.put("users", users);
                List<Dictionary> dictionaries = sysDictionaryService.list(new Dictionary("user-type"), null);
                result.put("dictionaries", dictionaries);
            }
            // 请求类型为获取收藏视频
            else if (Constants.ContentType.TYPE_VIDEO == type) {
                List<Video> videos = videoService.list(dataIds, contentType);
                result.put("videos", videos);
                List<Dictionary> dictionaries = sysDictionaryService.list(new Dictionary("production-type"), null);
                result.put("dictionaries", dictionaries);
            }
        }

        return RespBody.ok(result);
    }

    @ApiOperation(value = "API用户收藏", notes = "用户点击收藏/取消")
    @PostMapping(value = "/api/collect")
    @ResponseBody
    public RespBody collect(Collect collect) {
        try {
            User currentUser = WebUtil.getCurrentUser();
            collect.setUserId(currentUser.getId());
            collect.setDataId(collect.getDataId());
            collect.setType(collect.getType());
            collect.setOperation(collect.getOperation());

            Collect existCollect = userCollectService.get(collect);
            // 如果收藏信息存在, 则为取消收藏, 否则为收藏
            if (ObjectUtil.isNull(existCollect)) {
                userCollectService.save(collect);
                if (collect.getType().equals(2)) {
                    videoService.refresh(new Integer[]{collect.getDataId()});
                }
                return RespBody.ok(true);
            } else {
                userCollectService.delete(new Integer[]{existCollect.getId()});
                return RespBody.ok(false);
            }
        } catch (Exception e) {
            logger.error(super.translateI18N(Constants.Message.COLLECT_FAILED), e);
            return RespBody.error(super.translateI18N(Constants.Message.COLLECT_FAILED));
        }
    }

}
